package com.springboot_gradrecruit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.springboot_gradrecruit.common.PageResponse;
import com.springboot_gradrecruit.mapper.CollectMapper;
import com.springboot_gradrecruit.mapper.JobMapper;
import com.springboot_gradrecruit.mapper.SendMapper;
import com.springboot_gradrecruit.mapper.StudentMapper;
import com.springboot_gradrecruit.model.dto.send.PageSendRequest;
import com.springboot_gradrecruit.model.entity.Collect;
import com.springboot_gradrecruit.model.entity.Job;
import com.springboot_gradrecruit.model.entity.Send;
import com.springboot_gradrecruit.model.entity.Student;
import com.springboot_gradrecruit.model.vo.chart.SendRecordChange;
import com.springboot_gradrecruit.model.vo.chart.SendRecordSpread;
import com.springboot_gradrecruit.model.vo.job.JobVO;
import com.springboot_gradrecruit.model.vo.student.StudentVO;
import com.springboot_gradrecruit.service.SendService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author zr
* @description 针对表【send】的数据库操作Service实现
* @createDate 2024-11-08 09:53:14
*/
@Service
public class SendServiceImpl extends ServiceImpl<SendMapper, Send>
    implements SendService {

    @Resource
    private SendMapper sendMapper;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private StudentMapper studentMapper;

    @Override
    public PageResponse<JobVO> pageSendJob(PageSendRequest pageSendRequest) {
        //1.获取参数
        Long enterpriseId=pageSendRequest.getEnterpriseId();

        //2.构建查询条件，查询已收到投递的所有职位
        QueryWrapper<Send> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("enterprise_id",enterpriseId);
        queryWrapper.eq("send_status", "未回复");
        List<Send> sends = sendMapper.selectList(queryWrapper);
        if(sends.isEmpty()){
             return PageResponse.of(new Page<>(), JobVO.class);
        }
        List<Long> jobIds = sends.stream().map(Send::getJobId).toList();
        // 3.根据职位id查询职位信息
        QueryWrapper<Job> jobQueryWrapper = new QueryWrapper<>();
        jobQueryWrapper.in("job_id", jobIds);
        List<Job> jobs = jobMapper.selectList(jobQueryWrapper);

        // 4.将职位信息封装到 JobVO 对象中
        List<JobVO> jobVOS = jobs.stream().map(job -> {
            JobVO jobVO = BeanUtil.copyProperties(job, JobVO.class);
            return jobVO;

        }).toList();

        // 5.构建分页响应并返回
        PageResponse<JobVO> pageResponse = new PageResponse<>();
        pageResponse.setData(jobVOS);
        pageResponse.setTotal((long) jobVOS.size()); // 这里假设总记录数等于当前页记录数，可以根据实际需求调整
        long totalPages = (long) Math.ceil((double) jobVOS.size() / pageSendRequest.getPageSize());
        pageResponse.setPages(totalPages);
        return pageResponse;
    }

    @Override
    public PageResponse<StudentVO> pageSendStudent(PageSendRequest pageSendRequest) {
       //1.获取参数
        Long enterpriseId=pageSendRequest.getEnterpriseId();
        Long jobId=pageSendRequest.getJobId();
        Integer studentStatus=pageSendRequest.getStudentStatus();
        String studentHighestEducation=pageSendRequest.getStudentHighestEducation();
        String studentAddress=pageSendRequest.getStudentAddress();
        String searchName=pageSendRequest.getSearchName();

        //2.构建查询条件，查询企业收到到投递的学生
        QueryWrapper<Send> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("enterprise_id",enterpriseId);
        queryWrapper.eq("job_id",jobId);
        List<Send> sends = sendMapper.selectList(queryWrapper);
        if(sends.isEmpty()){
             return PageResponse.of(new Page<>(), StudentVO.class);
        }
        List<Long> studentIds = sends.stream().map(Send::getStudentId).toList();
        // 3.根据职位id查询学生信息，排除掉被封禁的学生
        LambdaQueryWrapper<Student> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Student::getStudentId,studentIds)
                .like(studentStatus!=null, Student::getStudentStatus, studentStatus)
                .like(StrUtil.isNotBlank(studentHighestEducation), Student::getStudentHighestEducation, studentHighestEducation)
                .like(StrUtil.isNotBlank(studentAddress), Student::getStudentAddress, studentAddress)
                .and(StrUtil.isNotBlank(searchName), w -> w.like(Student::getStudentName, searchName)
                        .or()
                        .like(Student::getStudentMajor, searchName)
                        .or()
                        .like(Student::getStudentGraduation, searchName));


        List<Student> students = studentMapper.selectList(lambdaQueryWrapper);

        // 4.将学生信息封装到 StudentVO 对象中
        List<StudentVO> studentVOS = students.stream().map(job -> {
            StudentVO studentVO = BeanUtil.copyProperties(job, StudentVO.class);
            return studentVO;

        }).toList();

        // 5.构建分页响应并返回
        PageResponse<StudentVO> pageResponse = new PageResponse<>();
        pageResponse.setData(studentVOS);
        pageResponse.setTotal((long) studentVOS.size()); // 这里假设总记录数等于当前页记录数，可以根据实际需求调整
        long totalPages = (long) Math.ceil((double) studentVOS.size() / pageSendRequest.getPageSize());
        pageResponse.setPages(totalPages);
        return pageResponse;
    }

    @Override
    public List<Send> queryRecentSendRecordsGroupByTime(Long enterpriseId) {

        //1.构建查询条件
        QueryWrapper<Send> queryWrapper = new QueryWrapper<>();
        // 根据企业ID筛选数据
        queryWrapper.eq("enterprise_id", enterpriseId);

        // 获取当前日期及对应的星期数（1表示星期一，7表示星期日）
        LocalDate currentDate = LocalDate.now();
        int currentDayOfWeek = currentDate.getDayOfWeek().getValue();

        // 计算起始日期（根据当天星期数确定往前推的天数，以得到近7周的数据）
        LocalDate startDate = currentDate.minusDays(currentDayOfWeek + (7 * 6));

        // 使用数据库函数（以MySQL为例）将日期与数据库中的create_time字段进行比较，筛选出相应范围的数据
        queryWrapper.apply("DATE(create_time) >= {0} AND DATE(create_time) <= {1}", startDate, currentDate);

//        queryWrapper.groupBy("create_time");
        queryWrapper.orderByDesc("create_time");

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public SendRecordSpread querySendRecordSpread(List<Send> sendList) {
        //1.创建对象
        SendRecordSpread sendRecordSpread = new SendRecordSpread();
        int collegeCount=0;//大专
        int bachelorCount=0;//本科
        int masterCount=0;//硕士
        int doctorCount=0;//博士
        int otherCount=0;//其他
        //2.遍历查询结果，统计数量
        for (Send send : sendList) {
            //2.1 获取学生最高学历
            String studentHighestEducation =studentMapper.selectById(send.getStudentId()).getStudentHighestEducation();
            switch (studentHighestEducation) {
                case "大专" -> collegeCount++;
                case "本科" -> bachelorCount++;
                case "硕士" -> masterCount++;
                case "博士" -> doctorCount++;
                default -> otherCount++;
            }
        }
        sendRecordSpread.setCollegeCount(collegeCount);
        sendRecordSpread.setBachelorCount(bachelorCount);
        sendRecordSpread.setMasterCount(masterCount);
        sendRecordSpread.setDoctorCount(doctorCount);
        sendRecordSpread.setOtherCount(otherCount);
        return sendRecordSpread;
    }

    @Override
    public SendRecordChange querySendRecordChange(List<Send> sendList) {
        //1.创建对象
        SendRecordChange sendRecordChange = new SendRecordChange();
        //2.遍历查询结果，统计数量
        int oneWeekCount=0;//一周内
        int twoWeekCount=0;//两周内
        int threeWeekCount=0;//三周内
        int fourWeekCount=0;//四周内
        int fiveWeekCount=0;//五周内
        int sixWeekCount=0;//六周内
        int sevenWeekCount=0;//一周内
        for (Send send : sendList) {
            //2.1 获取投递时间
            Date sendTime = send.getCreateTime();
            //2.2 计算时间差
            long timeDifference = System.currentTimeMillis() - sendTime.getTime();
            long daysDifference = TimeUnit.DAYS.convert(timeDifference, TimeUnit.MILLISECONDS);
            //2.3 根据时间差进行分类
            int week = (int) (daysDifference / 7);
            switch (week) {
                case 0 -> oneWeekCount++;
                case 1 -> twoWeekCount++;
                case 2 -> threeWeekCount++;
                case 3 -> fourWeekCount++;
                case 4 -> fiveWeekCount++;
                case 5 -> sixWeekCount++;
                case 6 -> sevenWeekCount++;
            }
        }
        sendRecordChange.setOneWeekCount(oneWeekCount);
        sendRecordChange.setTwoWeekCount(twoWeekCount);
        sendRecordChange.setThreeWeekCount(threeWeekCount);
        sendRecordChange.setFourWeekCount(fourWeekCount);
        sendRecordChange.setFiveWeekCount(fiveWeekCount);
        sendRecordChange.setSixWeekCount(sixWeekCount);
        sendRecordChange.setSevenWeekCount(sevenWeekCount);
        return sendRecordChange;
    }
}




